<template>
  <!-- 改写组件 -->
  <div class="con">
    <el-form
      :model="formData"
      label-width="70px"
      :inline="true"
      ref="formEle"
      class="flex formTop"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="formData.roleName"
          placeholder="请输入角色名称查找"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formEle)">查询</el-button>
        <el-button @click="resetForm(formEle)">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <div class="table-list">
      <div class="btnTop">
        <el-button type="primary" @click="handleAdd">添加新角色</el-button>
      </div>
      <el-table :data="RoleList" stripe style="width: 100%">
        <el-table-column
          v-for="(item, index) in columns"
          :key="index"
          :prop="item.property"
          :label="item.label"
          :formatter="item.formatter"
        ></el-table-column>
        <el-table-column label="操作" class="last-btn">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="primary"
              @click="handlePermission(scope.$index, scope.row)"
              >设置权限
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageData.pageSize"
        v-model:page-size="pageData.pageNum"
        :page-sizes="[1, 3, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <el-dialog
    v-model="dialogFormVisible"
    :title="dialogFormType == 'Edit' ? '编辑' : '创建角色'"
    @closed="clearDialog"
  >
    <el-form
      :model="dialogFormData"
      :label-width="formLabelWidth"
      ref="dialogForm"
    >
      <el-form-item label="用户名" prop="roleName">
        <el-input
          v-model="dialogFormData.roleName"
          placeholder="请输入用户名"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="dialogFormData.remark"
          autosize
          type="textarea"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogConfirm(dialogForm)">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog
    v-model="dialogTreeVisible"
    :title="dialogCurrentName"
    @closed="clearDialog"
    class="treeDialog"
  >
    <div>当前角色:</div>
    <el-tree
      :data="menuList"
      show-checkbox
      node-key="_id"
      default-expand-all
      :props="defaultProps"
      ref="dialogTree"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="TreeConfirm(dialogTree)">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, toRefs } from "vue";
import type { FormInstance } from "element-plus";
import { ElTree } from "element-plus";
import { formateDate, showMassage, classifyMenu } from "../untils/common";
import request from "../api/requestApi";
import { Getpermission } from "../untils/common";
import {
  GetRole,
  reqResult,
  ruleinfo,
  menuinfo,
  Setpermission,
  RuleInfo,
  permissionList,
} from "@/types/type";
import { log } from "console";
onMounted(async () => {
  await Promise.all([reqRoleList({}), reqMenuList()]);
});
// 查询表单数据
let formData = reactive({
  roleName: "",
});
let pageData = reactive({
  pageSize: 1, // 页数
  pageNum: 10, // 一页的数量
  total: 0, // 全部
});
// 总数
let { total } = toRefs(pageData);
let tableData = ref();

// 系统角色请求
async function reqRoleList(data: GetRole) {
  const res = (await request.getRoleList({ ...data })) as reqResult<RuleInfo>;
  RoleList.value = res.data.list;
  total.value = res.data.total;
}

// 菜单请求
let menuDic = reactive<any>({
  "630ad6e5f8d8464ddbdb9225": "部门管理",
  "630ffe76400bd79c6d04baf7": "待审批管理",
  "6302faa4d4a415792c9db14a": "休假申请",
  "630574f6f51f8c0d65db6738": "用户管理",
  "6305751bf51f8c0d65db6741": "菜单管理",
  "63057529f51f8c0d65db6744": "角色管理",
});   //字典映射

async function reqMenuList() {
  const res = (await request.getMenuList()) as reqResult<menuinfo[]>;
  let newarr: menuinfo[] = [];
  // 筛选菜单
  classifyMenu(newarr, res.data, "left");
  menuList.value = newarr;
  // 字典
  // menuDic = Getpermission(menuList.value);
}

const formEle = ref<FormInstance>();
// 搜索
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      reqRoleList({ ...formData, ...pageData });
      // const res = await request.getRoleList();
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};


// table字段
const columns = ref([
  {
    property: "roleName",
    label: "角色名称",
  },
  {
    property: "remark",
    label: "备注",
  },
  {
    property: "permissionList",
    label: "权限列表",
    formatter(roe: string, column: string, cellValue: permissionList) {
      let halfCheckedKeys = cellValue.halfCheckedKeys;
      let checkedKeys = cellValue.checkedKeys;
      let arr: string[] = [];
      halfCheckedKeys.map((item) => {
        if (menuDic[item]) {
          arr.push(menuDic[item]);
        }
      });
      checkedKeys.map((item) => {
        if (menuDic[item]) {
          arr.push(menuDic[item]);
        }
      });
      return arr.join(" ");
    },
  },
  {
    property: "createTime",
    label: "注册时间",
    formatter(roe: string, column: string, cellValue: string) {
      return formateDate(new Date(cellValue));
    },
  },
  {
    property: "updateTime",
    label: "更新时间",
    formatter(roe: string, column: string, cellValue: string) {
      return formateDate(new Date(cellValue));
    },
  },
]);
// 角色列表
let RoleList = ref();


// 新增 编辑 修改 设置权限按钮
function handleAdd() {
  openDialog("Add");
}
async function handleEdit(index: number, row: ruleinfo) {
  openDialog("Edit");
  Object.assign(dialogFormData, row);
  let res = (await request.EditRole(dialogFormData)) as reqResult<null>;
  reqRoleList({ ...formData, ...pageData });
}
async function handleDelete(index: number, row: ruleinfo) {
  console.log("删除", row);
  let res = (await request.DelRole(row._id)) as reqResult<null>;
  reqRoleList(formData);
}
function handlePermission(index: number, row: ruleinfo) {
  dialogCurrentName.value = "设置权限(" + row.roleName + ")";
  Object.assign(dialogTreeData, row);
  const { checkedKeys } = row.permissionList!;
  dialogTreeVisible.value = true;
  reqMenuList();
  nextTick(() => {
    dialogTree.value!.setCheckedKeys(checkedKeys);
  });
}
function openDialog(type: string) {
  dialogFormVisible.value = true;
  dialogFormType.value = type;
}





// dialog 对话框
const dialogFormVisible = ref(false); // 开关
const dialogFormType = ref<string>("");
const formLabelWidth = "70px";
const dialogForm = ref(null);
const dialogFormData = reactive<ruleinfo>({
  roleName: "",
  remark: "",
});
// 树状结构对话框
let menuList = ref<menuinfo[]>([]);
let dialogTreeVisible = ref<boolean>(false);
let dialogTree = ref<InstanceType<typeof ElTree>>();
let dialogCurrentName = ref();
const dialogTreeData = reactive<ruleinfo>({
  roleName: "",
  remark: "",
});
let defaultProps = {
  children: "children",
  label: "menuName",
};

// 对话框确认
function dialogConfirm(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let res: reqResult<null> = {
        data: null,
        msg: "",
        code: 0,
      };
      if (dialogFormType.value == "Add") {
        res = (await request.AddRole(dialogFormData)) as reqResult<null>;
      } else if (dialogFormType.value == "Edit") {
        res = (await request.EditRole(dialogFormData)) as reqResult<null>;
      }
      // 参数错误
      if (res.code == 200) {
        showMassage(res.msg, "success");
        reqRoleList(formData);
      } else {
        showMassage(res.msg, "error");
      }
    } else {
      console.log(fields);
    }
  });
  dialogFormVisible.value = false;
}
// 树形对话框确认
async function TreeConfirm(dialogTree: InstanceType<typeof ElTree>) {
  if (!dialogTree) return;
  // ! 非空断言
  let params: Setpermission = {
    _id: dialogTreeData!._id!,
    permissionList: {
      checkedKeys: dialogTree.getCheckedKeys(),
      halfCheckedKeys: dialogTree.getHalfCheckedKeys(),
    },
  };
  let res = (await request.PerRole({ ...params })) as reqResult<null>;
  if (res.code == 200) {
    Promise.all([reqRoleList(formData), reqMenuList()]);
    showMassage(res.msg, "success");
  } else {
    showMassage(res.msg, "error");
  }
  dialogTreeVisible.value = false;
}
// 关闭对话框
function clearDialog() {
  dialogFormVisible.value = false;
  dialogFormData.roleName = "";
  dialogFormData.remark = "";
}
// 改变当前页
const handleCurrentChange = (value: number) => {
  pageData.pageSize = value;
  reqRoleList({ ...formData, ...pageData });
};
// 改变一页的个数
const handleSizeChange = (value: number) => {
  pageData.pageNum = value;
  reqRoleList({ ...formData, ...pageData });
};
</script>

<style lang="postcss" scoped>
.con {
  @apply flex-1 flex flex-col;
  width: 100%;
}
.formTop {
  height: 60px;
  padding: 20px;
  @apply bg-light-50;
  line-height: 60px;
  border-radius: 5px;
  .el-form-item {
    margin-bottom: 0;
    align-self: center;
  }
}
.table-list {
  @apply bg-light-50 flex-1 flex flex-col;
  border-radius: 5px;
  overflow: hidden;
  margin: 20px 0 0 0;
  .btnTop {
    padding: 20px;
  }
  .el-pagination {
    margin: auto auto 0;
    height: 50px;
  }
}
.el-table :deep(.el-table__cell) {
  padding: 15px 15px;
}
/* .treeDialog :deep(.el-dialog__body) {
  padding-top: 0px;
}
.treeDialog ::v-deep .el-dialog__body {
  padding-top: 0px;
} */
</style>
